package cn.yunyichina.provider.base.service.impl;

import cn.yunyichina.provider.base.dao.PersonalUserDao;
import cn.yunyichina.provider.base.dao.PersonalUserOpenidDao;
import cn.yunyichina.provider.base.dao.PersonalUserRelationDao;
import cn.yunyichina.provider.base.utils.FamilyConstants;
import cn.yunyichina.provider.base.utils.IdCardUtils;
import cn.yunyichina.provider.base.vo.AddPersonalUserRequest;
import cn.yunyichina.provider.base.vo.PersonalUserRequest;
import cn.yunyichina.provider.base.vo.PersonalUserResponseVo;
import cn.yunyichina.provider.iface.entity.PersonalUser;
import cn.yunyichina.provider.iface.entity.PersonalUserOpenid;
import cn.yunyichina.provider.iface.entity.PersonalUserRelation;
import cn.yunyichina.provider.iface.entity.common.Response;
import cn.yunyichina.provider.iface.entity.common.ResponseObject;
import cn.yunyichina.utils.commons.DateUtils;
import cn.yunyichina.utils.commons.IDUtils;
import cn.yunyichina.utils.convert.JsonUtils;
import com.alibaba.dubbo.common.utils.CollectionUtils;
import com.alibaba.dubbo.common.utils.StringUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@Service("personaluserServiceImpl")
public class PersonalUserServiceImpl extends BaseSelectService {
    private static Logger logger = LoggerFactory.getLogger(PersonalUserServiceImpl.class);
    public static DateFormat YYYYMMDD = new SimpleDateFormat("yyyy-MM-dd");
    public static DateFormat YYYYMMDD8 = new SimpleDateFormat("yyyyMMdd");
    @Autowired
    private PersonalUserDao personalUserDao;
    @Autowired
    private PersonalUserRelationDao personalUserRelationDao;
    @Autowired
    private PersonalUserOpenidDao personalUserOpenidDao;

    /**
     * 通用查询
     *
     * @param strJson 对应数据库字段名
     * @return
     */
    public List<PersonalUser> list(String strJson) {
        return super.listEntity(strJson, PersonalUser.class, personalUserDao);
    }

    /**
     * 删除就诊人
     *
     * @param strJson
     * @return
     */
    public ResponseObject deletePersonalUser(String strJson) {
        logger.info("deletePersonalUser strJson = {}", new Object[]{strJson});
        JSONObject jsonObj = JSONObject.parseObject(strJson);
        String userId = jsonObj.getString("user_id");
        String relationUserId = jsonObj.getString("relation_per_user_id");
        ResponseObject response = new ResponseObject();

        if (StringUtils.isBlank(userId) || StringUtils.isBlank(relationUserId)) {
            response.setResultCodeAndMessage("1002", "user_id ,relation_per_user_id 不能为空");
            return response;
        }

        try {
            personalUserRelationDao.deleteByUserIdAndRelationUserId(userId, relationUserId);
            response.setResultCodeAndMessage("0", "删除就诊人成功");
        } catch (Exception e) {
            e.printStackTrace();
            response.setResultCodeAndMessage("1998", "删除就诊人失败");
        }
        return response;
    }

    private String checkAddPersonalUserRequest(AddPersonalUserRequest request ){
        String errMsg ="";
        if (request.getPatType() == null || StringUtils.isBlank(request.getPatName()) || request.getRelationType() == null) {
            errMsg = "patType,patName ,relationType 不能为空";
            return errMsg;
        }
        if (request.getRelationType() != 0 && StringUtils.isBlank(request.getPerUserId())) {
            errMsg = "增加他人信息 per_user_id 不能为空";
            return errMsg;
        }

        if (request.getPatType()== 1 && (StringUtils.isBlank(request.getPatIdNo()) && request.getPatIdType() == null)) {
            errMsg = "添加成功就诊人 id_card_no ,id_card_type 不能为空";
            return errMsg;
        }
        if (!StringUtils.isBlank(request.getPatIdNo()) && 1 == request.getPatIdType()) {
            if (!IdCardUtils.validateCard(request.getPatIdNo())) {
                errMsg = "身份证格式错误";
                return errMsg;
            }
        }
        return errMsg;
    }

    /**
     * 添加就诊人接口
     *
     * @param strJson
     * @return
     * @throws Exception
     */
    @Transactional
    public ResponseObject addPersonalUser(String strJson) throws Exception {
        logger.info("addPersonalUser strJson = {}", new Object[]{strJson});
        AddPersonalUserRequest request = JsonUtils.parseObject(strJson, AddPersonalUserRequest.class);
        ResponseObject response = new ResponseObject();
        String errMsg = checkAddPersonalUserRequest(request);
        if (!StringUtils.isBlank(errMsg)){
            response.setResultCodeAndMessage("1002",errMsg);
            return response;
        }


        try {
            /**成人*/
            if (FamilyConstants.USER_TYPE_ADULT == request.getPatType()) {
                /**本人*/
                /**库中之前是否已经有身份证*/
                PersonalUser personalUser = personalUserDao.getByIdCardNo(request.getPatIdType(), request.getPatIdNo());
                /**该手机号码是否已经被注册*/
                PersonalUser loginPersonalUser = personalUserDao.selectByLoginName(request.getPatMobile());

                if (FamilyConstants.FAMILY_OWNERSHIP_SELF == request.getRelationType()) {
                    logger.info("新增关系类型为本人的就诊人 pat_id_no ={}", new Object[]{request.getPatIdNo()});
                    try {
                        if (personalUser != null) {
                            logger.info("已经存在关系类型为本人的就诊人");
                            if (personalUser.getUserName() !=null && !personalUser.getUserName().equals(request.getPatName())){
                                response.setResultCodeAndMessage("1003", "该身份证对应的姓名不一致，请重新绑卡");
                                return response;
                            }
                            updatePersonal(request, personalUser, loginPersonalUser);
                        } else {
                            /**插入新记录*/
                            logger.info("新增一条关系类型为（本人）的就诊人 pat_id_no ={}", new Object[]{request.getPatIdNo()});
                            personalUser = insertPersonalUser(request, loginPersonalUser);
                        }

                        logger.info("本人需要新增openid 关系表");
                        PersonalUserOpenid dbPersonalUserOpenid = personalUserOpenidDao.selectByOpenId(request.getOpenId(),request.getAppId() );
                        if (dbPersonalUserOpenid ==null) {
                            /**可能是他人转本人的情况 之前没有在open_id 表有记录*/
                            PersonalUserOpenid personalUserOpenid = buildPersonalUserOpenid(personalUser, request);
                            personalUserOpenidDao.insert(personalUserOpenid);
                        }else {
                            if (!dbPersonalUserOpenid.getPerUserId().equals(personalUser.getId())){
                                response.setResultCodeAndMessage("1003", "失败,open_id 已被占用");
                                return response;
                            }
                        }

                        response.setResultCodeAndMessageAndResult("0", "成功", buildPersonalUserResponseVo(personalUser));
                    } catch (Exception e) {
                        e.printStackTrace();
                        logger.info("新增就诊人异常");
                        response.setResultCodeAndMessage("1998", "新增就诊人异常");
                        return response;
                    }

                } else {
                    try {
                        /**他人*/
                        if (personalUser != null) {
                            logger.info("已经存在关系类型为(他人)的就诊人");
                            if (personalUser.getUserName() !=null && !personalUser.getUserName().equals(request.getPatName())){
                                response.setResultCodeAndMessage("1003", "该身份证对应的姓名不一致，请重新绑卡");
                                return response;
                            }
                            updatePersonal(request, personalUser, loginPersonalUser);
                        } else {
                            logger.info("新增关系类型为（他人）的就诊人 pat_id_no ={}", new Object[]{request.getPatIdNo()});
                            personalUser = insertPersonalUser(request, loginPersonalUser);
                        }

                        PersonalUserRelation personalUserRelation = personalUserRelationDao.selectByPerUserIdAndRelationUserId(request.getPerUserId(),personalUser.getId());
                        if (personalUserRelation == null) {
                            logger.info("新增一条本人跟他人的关系记录");
                            personalUserRelation = buildPersonalUserRelation(personalUser, request);
                            personalUserRelationDao.insert(personalUserRelation);
                        }
                        response.setResultCodeAndMessageAndResult("0", "成功", buildPersonalUserResponseVo(personalUser));
                        return response;

                    } catch (Exception e) {
                        e.printStackTrace();
                        logger.info("增加他人类型的就诊人出错");
                        response.setResultCodeAndMessage("1998", "增加他人类型的就诊人出错");
                        return response;
                    }
                }
            } else {
                /**儿童*/
                //// TODO: 2017/3/7
                PersonalUser personalUser = buildChildPersonalUser(request);
                personalUserDao.insert(personalUser);

                PersonalUserRelation personalUserRelation = buildPersonalUserRelation(personalUser, request);
                personalUserRelationDao.insert(personalUserRelation);
                response.setResultCodeAndMessageAndResult("0", "成功",buildPersonalUserResponseVo(personalUser));
            }

        } catch (Exception e) {
            e.printStackTrace();
            response.setResultCodeAndMessage("1998", "系统异常");

        }
        return response;
    }

    private PersonalUserResponseVo buildPersonalUserResponseVo(PersonalUser personalUser ){
        PersonalUserResponseVo result  = new PersonalUserResponseVo();
        result.setId(personalUser.getId());
        result.setPatBirth(personalUser.getBirth());
        result.setWechat(personalUser.getWechat());
        result.setPatType(personalUser.getUserType());
        result.setPatMobile(personalUser.getMobile());
        result.setPatSex(personalUser.getSex());
        result.setPatName(personalUser.getUserName());
        result.setPatIdType(personalUser.getIdCardType());
        result.setPatIdNo(personalUser.getIdCardNo());
        result.setPatAddress(personalUser.getAddress());
        result.setLoginName(personalUser.getLoginName());
        result.setPassword(personalUser.getPassword());
        result.setNickName(personalUser.getNickName());
        result.setHeadImg(personalUser.getHeadImg());
        result.setEnableFlag(personalUser.getEnableFlag());
        result.setDescription(personalUser.getDescription());
        result.setCityName(personalUser.getCityName());
        result.setCityId(personalUser.getCityId());
        result.setBeginRegisterTime(personalUser.getBeginRegisterTime());
        result.setBeginLastLoginTime(personalUser.getBeginLastLoginTime());
        result.setAreaName(personalUser.getAreaName());
        result.setAreaId(personalUser.getAreaId());
        result.setQq(personalUser.getQq());
        return result;
    }

    private PersonalUser insertPersonalUser(AddPersonalUserRequest request, PersonalUser loginPersonalUser) throws Exception {
        PersonalUser personalUser;
        String loginName = request.getPatMobile();
        /**用身份证查到的人，跟用登录名（手机号码）查到的人不一致。那么本次新增的这个人就不能使用该手机号码了*/
        if (loginPersonalUser != null) {
            for (int i = 1; i < 10; i++) {
                loginPersonalUser = personalUserDao.selectByLoginName(request.getPatMobile() + "_" + i);
                if (loginPersonalUser == null) {
                    loginName = request.getPatMobile() + "_" + i;
                    break;
                }
            }
        }
        personalUser = buildPersonalUser(request);
        personalUser.setLoginName(loginName);
        personalUserDao.insert(personalUser);
        return personalUser;
    }

    private void updatePersonal(AddPersonalUserRequest request, PersonalUser personalUser, PersonalUser loginPersonalUser) {
        String loginName = request.getPatMobile();
        /**用身份证查到的人，跟用登录名（手机号码）查到的人不一致。那么本次新增的这个人就不能使用该手机号码了*/
        if (loginPersonalUser != null && !personalUser.getId().equals(loginPersonalUser.getId())) {
            for (int i = 1; i < 10; i++) {
                loginPersonalUser = personalUserDao.selectByLoginName(request.getPatMobile() + "_" + i);
                if (loginPersonalUser == null || (loginPersonalUser != null && personalUser.getId().equals(loginPersonalUser.getId()))) {
                    loginName = request.getPatMobile() + "_" + i;
                    break;
                }
            }
        }
        personalUser.setLoginName(loginName);
        personalUser.setMobile(request.getPatMobile());
        personalUser.setUserName(request.getPatName());
        personalUserDao.update(personalUser);
    }

    /**
     * 构建儿童就诊人对象
     *
     * @param request
     * @return
     */
    private PersonalUser buildChildPersonalUser(AddPersonalUserRequest request) throws Exception {
        PersonalUser personalUser = new PersonalUser();
        personalUser.setUserType(request.getPatType());
        personalUser.setEnableFlag(new Short("1"));
        personalUser.setSex(request.getPatSex());
        personalUser.setUserName(request.getPatName());
        personalUser.setBirth(YYYYMMDD.format(YYYYMMDD.parse(request.getPatBirth())));
        //随机生成
        personalUser.setLoginName(IDUtils.getUUID32());
        personalUser.setPassword("123456");
        personalUser.setSalt("123456");
        personalUser.setRegisterTime(DateUtils.dateToString(new Date()));
        personalUser.setLastLoginTime(DateUtils.dateToString(new Date()));
        return personalUser;

    }


    private PersonalUserRelation buildPersonalUserRelation(PersonalUser personalUser, AddPersonalUserRequest request) {
        PersonalUserRelation personalUserRelation = new PersonalUserRelation();
        personalUserRelation.setId(IDUtils.getUUID32());
        //本人的id
        personalUserRelation.setPerUserId(request.getPerUserId());
        personalUserRelation.setRelationPerUserId(personalUser.getId());
        //personalUserRelation.setPerUserName();
        personalUserRelation.setRelationPerUserName(personalUser.getUserName());
        personalUserRelation.setRelationType(request.getRelationType());
        personalUserRelation.setState(new Short("1"));
        return personalUserRelation;
    }


    private PersonalUserOpenid buildPersonalUserOpenid(PersonalUser personalUser, AddPersonalUserRequest request) {
        PersonalUserOpenid personalUserOpenid = new PersonalUserOpenid();
        personalUserOpenid.setId(IDUtils.getUUID32());
        personalUserOpenid.setAppId(request.getAppId());
        personalUserOpenid.setPerUserId(personalUser.getId());
        personalUserOpenid.setOpenId(StringUtils.isBlank(request.getOpenId()) ? personalUser.getId() : request.getOpenId());
        return personalUserOpenid;
    }

    /**
     * 构建成人就诊人对象
     *
     * @return PersonalUser
     * @throws Exception
     */
    private PersonalUser buildPersonalUser(AddPersonalUserRequest request) throws Exception {

        PersonalUser personalUser = new PersonalUser();

        personalUser.setId(IDUtils.getUUID32());

        //登陆名，默认手机，如果手机为空，则为身份证
        personalUser.setLoginName(request.getPatMobile());
        personalUser.setPassword("123456");
        personalUser.setSalt("123456");
        personalUser.setUserName(request.getPatName());
        personalUser.setNickName(request.getNickName());
        personalUser.setEmail(request.getPatEmail());
        personalUser.setQq(request.getQq());
        personalUser.setWechat(request.getWechat());
        personalUser.setHeadImg(request.getHeadImg());
        personalUser.setIdCardType(request.getPatIdType() == null ? new Short("1") : request.getPatIdType());
        personalUser.setIdCardNo(request.getPatIdNo());
        if (request.getPatIdType()!=null && request.getPatIdType()==1){
            personalUser.setBirth(YYYYMMDD.format(YYYYMMDD8.parse(IdCardUtils.getBirthByIdCard(request.getPatIdNo()))));
        }

        personalUser.setMobile(request.getPatMobile());
        if (request.getPatSex() !=null){
            personalUser.setSex(request.getPatSex());
        }else {
            if (request.getPatIdType()!=null && request.getPatIdType()==1){
                personalUser.setSex(convertSex(IdCardUtils.getGenderByIdCard(request.getPatIdNo())));
            }
        }
        personalUser.setUserType(request.getPatType());
        personalUser.setProvinceId(request.getProvinceId());
        personalUser.setProvinceName(request.getProvinceName());
        personalUser.setCityId(request.getCityId());
        personalUser.setCityName(request.getCityName());
        personalUser.setAreaId(request.getAreaId());
        personalUser.setAreaName(request.getAreaName());
        personalUser.setAddress(request.getPatAddress());
        personalUser.setDescription(request.getDescription());
        /**默认启用     是否启用        0-禁用      1-启用',*/
        personalUser.setEnableFlag(new Short("1"));
        personalUser.setRegisterTime(DateUtils.dateToString(new Date()));
        personalUser.setLastLoginTime(DateUtils.dateToString(new Date()));
        return personalUser;
    }

    private Short convertSex(String sex) {
        if (StringUtils.isNotEmpty(sex)) {
            if ("M".equals(sex)) {
                return 1;
            } else if ("F".equals(sex)) {
                return 2;
            }
            return 3;
        }
        return 3;
    }


    /**
     * 获取本人及家人列表
     *
     * @param strJson
     * @return
     */
    public ResponseObject listPersonalUser(String strJson) {
        logger.info("listPersonalUser strJson = {}", new Object[]{strJson});
        ResponseObject response = new ResponseObject();

        try {
            PersonalUserRequest request = JsonUtils.parseObject(strJson, PersonalUserRequest.class);
            String userId = request.getUserId();

            if (StringUtils.isBlank(userId)) {
                response.setResultCodeAndMessage("1001", "user_id 不能空");
                return response;
            }

            if(request.getRequestType() !=null && request.getRequestType()==1){
                String openId = userId;
                logger.info("通过Open_id 查询就诊人列表 open_id={}",new Object[]{openId});
                PersonalUserOpenid dbPersonalUserOpenid = personalUserOpenidDao.selectByOpenId(openId, request.getAppId());
                if (dbPersonalUserOpenid ==null){
                    response.setResultCodeAndMessage("1002", "该openid 未绑定过就诊人");
                    return response;
                }
                List<String> userIds = new ArrayList<>();
                userIds.add(dbPersonalUserOpenid.getPerUserId());

                PersonalUser personalUser = personalUserDao.selectById(dbPersonalUserOpenid.getPerUserId());

                if (null == personalUser) {
                    response.setResultCodeAndMessage("1002", "该用户不存在或者不可用");
                    return response;
                }

                Map<String, PersonalUserRelation> personalUserRelationMap = new HashMap<>();
                List<PersonalUserRelation> personalUserRelations = personalUserRelationDao.selectByPerUserId(dbPersonalUserOpenid.getPerUserId());
                if (CollectionUtils.isNotEmpty(personalUserRelations)) {
                    for (PersonalUserRelation pr : personalUserRelations) {
                        personalUserRelationMap.put(pr.getRelationPerUserId(), pr);
                        userIds.add(pr.getRelationPerUserId());
                    }
                }
                List<PersonalUser> personalUserList = personalUserDao.selectByIds(userIds);
                userId = dbPersonalUserOpenid.getPerUserId();
                List<PersonalUserResponseVo> personalUserVoList = getPersonalUserResponseVos(userId, personalUserRelationMap, personalUserList);
                response.setResultCodeAndMessageAndResult("0", "成功", personalUserVoList);
            }else {
                List<String> userIds = new ArrayList<>();
                userIds.add(userId);
                PersonalUser personalUser = personalUserDao.selectById(userId);

                if (null == personalUser) {
                    response.setResultCodeAndMessage("1002", "该用户不存在或者不可用");
                    return response;
                }

                Map<String, PersonalUserRelation> personalUserRelationMap = new HashMap<>();
                List<PersonalUserRelation> personalUserRelations = personalUserRelationDao.selectByPerUserId(userId);
                if (CollectionUtils.isNotEmpty(personalUserRelations)) {
                    for (PersonalUserRelation pr : personalUserRelations) {
                        personalUserRelationMap.put(pr.getRelationPerUserId(), pr);
                        userIds.add(pr.getRelationPerUserId());
                    }
                }
                List<PersonalUser> personalUserList = personalUserDao.selectByIds(userIds);
                List<PersonalUserResponseVo> personalUserVoList = getPersonalUserResponseVos(userId, personalUserRelationMap, personalUserList);
                response.setResultCodeAndMessageAndResult("0", "成功", personalUserVoList);
            }

        }catch (Exception e){
            logger.error("查询就诊人列表出错",e);
            response.setResultCodeAndMessage("-1","查询就诊人列表出错");
            return response;
        }
        return response;
    }

    private List<PersonalUserResponseVo> getPersonalUserResponseVos(String userId, Map<String, PersonalUserRelation> personalUserRelationMap, List<PersonalUser> personalUserList) {
        List<PersonalUserResponseVo> personalUserVoList = new ArrayList<>();
        for (PersonalUser personalUser : personalUserList) {
            PersonalUserResponseVo result  = new PersonalUserResponseVo();
            result.setId(personalUser.getId());
            result.setPatBirth(personalUser.getBirth());
            result.setWechat(personalUser.getWechat());
            result.setPatType(personalUser.getUserType());
            result.setPatMobile(personalUser.getMobile());
            result.setPatSex(personalUser.getSex());
            result.setPatName(personalUser.getUserName());
            result.setPatIdType(personalUser.getIdCardType());
            result.setPatIdNo(personalUser.getIdCardNo());
            result.setPatAddress(personalUser.getAddress());
            result.setLoginName(personalUser.getLoginName());
            result.setPassword(personalUser.getPassword());
            result.setNickName(personalUser.getNickName());
            result.setHeadImg(personalUser.getHeadImg());
            result.setEnableFlag(personalUser.getEnableFlag());
            result.setDescription(personalUser.getDescription());
            result.setCityName(personalUser.getCityName());
            result.setCityId(personalUser.getCityId());
            result.setBeginRegisterTime(personalUser.getBeginRegisterTime());
            result.setBeginLastLoginTime(personalUser.getBeginLastLoginTime());
            result.setAreaName(personalUser.getAreaName());
            result.setAreaId(personalUser.getAreaId());
            result.setQq(personalUser.getQq());
            /**设置关系 关系类型\r\n
             relationt_ype 0本人 ， 1父母，2子女，兄妹，4伴侣，5其它\r\n
             */
            if (userId.equals(personalUser.getId())) {
                result.setRelationType(new Short("0"));
            } else {
                result.setRelationType(personalUserRelationMap.get(personalUser.getId()).getRelationType());
            }
            personalUserVoList.add(result);
        }
        return personalUserVoList;
    }

    public ResponseObject getPersonalUserByOpenId(String strJson) {
        ResponseObject response = new ResponseObject();

        try {
            JSONObject request = JSONObject.parseObject(strJson);
            String openId = request.getString("open_id");

            if (StringUtils.isBlank(openId)) {
                response.setResultCodeAndMessage("1001", "opend_id 不能空");
                return response;
            }
            PersonalUserOpenid personalUserOpenid = personalUserOpenidDao.selectByOpenId(openId,request.getString("app_id"));
            if (personalUserOpenid == null){
                response.setResultCodeAndMessage("1002", "该openid 未绑定过就诊人");
                return response;
            }

            PersonalUser personalUser = personalUserDao.selectById(personalUserOpenid.getPerUserId());

            response.setResultCodeAndMessageAndResult("0","成功",buildPersonalUserResponseVo(personalUser));
            return response;
        }catch (Exception e){
            logger.error("根据opend_id查询就诊人出错",e);
            response.setResultCodeAndMessage("-1","根据opend_id查询就诊人出错系统异常");
            return response;
        }

    }


    /**
     * 根据证件号和证件类型获取用户对象
     *
     * @param idCardNo
     * @param idCardType 1：二代身份证，               2：港澳居民身份证，               3：台湾居民身份证，               4：护照
     * @return 如果没有找到，或者参数为空的，返回null。如果找到多个，返回第一个
     */
    public PersonalUser getPersonalUserByIdCardNo(String idCardNo, short idCardType) {
        if (!StringUtils.isEmpty(idCardNo)) {
            PersonalUser personalUser = new PersonalUser();
            personalUser.setIdCardNo(idCardNo);
            personalUser.setIdCardType(idCardType);
            List<PersonalUser> listPersonalUser = personalUserDao.select(personalUser);
            if (CollectionUtils.isEmpty(listPersonalUser)) {
                return null;
            } else {
                return listPersonalUser.get(0);
            }
        }
        return null;
    }

    /**
     * 根据身份证获取用户对象
     *
     * @param mobile
     * @return 如果没有找到，或者参数为空的，返回null。如果找到多个，返回第一个
     */
    public PersonalUser getPersonalUserByMobile(String mobile) {
        if (!StringUtils.isEmpty(mobile)) {
            PersonalUser personalUser = new PersonalUser();
            personalUser.setMobile(mobile);
            List<PersonalUser> listPersonalUser = personalUserDao.select(personalUser);
            if (CollectionUtils.isEmpty(listPersonalUser)) {
                return null;
            } else {
                return listPersonalUser.get(0);
            }
        }
        return null;
    }

    public ResponseObject updatePersonalUser(String data){
        logger.info("[PersonalUserServiceImpl.updatePersonalUser] 更新用户信息入参：" + JsonUtils.toJsonString(data));
        ResponseObject responseObject = new ResponseObject();
        Short age=null;
        try {
            PersonalUserRequest request = JsonUtils.parseObject(data, PersonalUserRequest.class);
            if (StringUtils.isBlank(request.getUserId())){
                responseObject.setResultCodeAndMessage("1001","参数缺失user_id 不能为空");
                return responseObject;
            }
            PersonalUser personalUserQuery=personalUserDao.selectById(request.getUserId());
            if(personalUserQuery!=null){
                age = (short)cn.yunyichina.utils.commons.IdCardUtils.getAgeByBirth(request.getBirth());
                PersonalUser personalUser = new PersonalUser();
                personalUser.setMobile(request.getMobile());
                personalUser.setUserName(request.getUserName());
                personalUser.setSex(request.getSex());
                personalUser.setBirth(request.getBirth());
                personalUser.setAge(age);
                personalUser.setHeadImg(request.getHeadImg());
                personalUser.setId(request.getUserId());
                personalUserDao.update(personalUser);
                responseObject.setResultCodeAndMessage("0","成功");
            }else {
                responseObject.setResultCodeAndMessage("1001","用户不存在");
            }
        } catch (ParseException e) {
            logger.info("更新用户信息格式化异常:"+e.getCause());
            responseObject.setResultCodeAndMessage("1999","更新用户信息失败");
        } catch (Exception e){
            logger.info("更新用户信息失败:"+e.getCause());
            responseObject.setResultCodeAndMessage("1999","更新用户信息失败");
        }
        return responseObject;
    }

    /**
     * yyt.base.personaluser.by.id.get
     * @param data
     * @return
     */
    public ResponseObject getPersonalUserById(String data){
        logger.info("[PersonalUserServiceImpl.getPersonalUserById] 查询用户信息入参：" + JsonUtils.toJsonString(data));
        ResponseObject responseObject = new ResponseObject();
        try {
            PersonalUserRequest request = JsonUtils.parseObject(data, PersonalUserRequest.class);
            if (StringUtils.isBlank(request.getUserId())){
                responseObject.setResultCodeAndMessage("1001","参数缺失user_id 不能为空");
                return responseObject;
            }
            PersonalUser personalUserQuery=personalUserDao.selectById(request.getUserId());
            if(personalUserQuery!=null){
                responseObject.setResultObject(personalUserQuery);
            }else {
                responseObject.setResultCodeAndMessage("1001","查询用户不存在");
            }
        }catch (Exception e){
            logger.info("更新用户信息失败:"+e.getCause());
            responseObject.setResultCodeAndMessage("1999","查询用户信息失败");
        }
        return responseObject;
    }

    /**
     * 根据OpenId获取用户授权手机号
     *
     * @param datas
     * @interfaceName:yyt.base.personalUser.mobile.by.openid.get
     * @return
     */
    public ResponseObject getPersonalUserMobileByOpenId(String datas) {
        ResponseObject response = new ResponseObject();
        Map<String, String> dataMap = JSON.parseObject(datas, Map.class);
        String openId = dataMap.get("open_id");

        if(!StringUtils.isEmpty(openId)){
            PersonalUserOpenid userOpenid = new PersonalUserOpenid();
            userOpenid.setOpenId(openId);
            List<PersonalUserOpenid> userOpenids = personalUserOpenidDao.select(userOpenid);
            if(userOpenids.size() > 0){
                PersonalUserOpenid personalUserOpenid = userOpenids.get(0);
                if(!StringUtils.isEmpty(personalUserOpenid.getPerUserId())){
                    PersonalUser personalUser = new PersonalUser();
                    personalUser.setId(personalUserOpenid.getPerUserId());
                    List<PersonalUser> personalUsers = personalUserDao.select(personalUser);
                    response.setResultCodeAndMessageAndResult(Response.SUCCESS_CODE , Response.SUCCESS_MESSAGE , personalUsers.get(0));
                }else{
                    response.setResultCodeAndMessageAndResult(Response.FAILURE_CODE , "Get PerUserId is null!" , null);
                }
            }else{
                response.setResultCodeAndMessageAndResult(Response.FAILURE_CODE , "Get PersonalUserOpenid List size < 1!" , null);
            }
        }else{
            response.setResultCodeAndMessageAndResult(Response.FAILURE_CODE , "openId is null!" , null);
        }
        return response;
    }
}
